package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.PlanApproveAdapter;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.base.BaseSingleChoiceDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.HintNumber;
import com.isunland.managesystem.entity.PlanList;
import com.isunland.managesystem.entity.PlanList.PlanCheckList;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONException;

/**
 * 计划审核
 *
 * @author yuhaohao
 */
public class PlanApproveListFragment extends BaseListFragment {

  public static final String EXTRA_TYPE = "com.isunland.managesystem.ui.extra_type";
  public static final int VALUE_PERSON = 0;
  public static final int VALUE_DEPT = 1;
  public static final int VALUE_APPROVEV = 0;
  public static final int VALUE_OBJECT = 1;
  private static final int REQUEST_CHOICE = 0;

  private PlanApproveAdapter mPlanApproveAdapter;

  HashMap<String, String> planPersonal;
  private BaseVolleyActivity mActivity = null;
  /**
   * 分为部门和个人，用于传参数时判断
   */
  private int mType;
  private String mId;
  /**
   * 同意反对
   */
  private int[] mChoiceIds;
  private DialogFragment mDialog;
  private FragmentManager mFm;
  private String mAgree;
  private String mAgainst;
  private PlanCheckList mContent;

  @Override public HashMap<String, String> getparameters() {
    planPersonal = new HashMap<>();
    planPersonal.put("curPage", "1");
    planPersonal.put("pageSize", "10000");

    if (mType == VALUE_PERSON) {
      planPersonal.put("checkType", "person");
    } else {
      planPersonal.put("checkType", "dept");
    }
    return planPersonal;
  }

  @Override public String getUrl() {

    return ApiConst.URL_PLANAPPROVE_LIST;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    mType = getArguments().getInt(EXTRA_TYPE);
    mActivity = (BaseVolleyActivity) getActivity();

    mChoiceIds = new int[] { R.string.agreed, R.string.against, R.string.detail, };
    mAgree = getResources().getString(R.string.agree);
    mAgainst = getResources().getString(R.string.against);
    mAgainst = getResources().getString(R.string.detail);
    // 初始化单选对话框.
    mDialog = BaseSingleChoiceDialogFragment.newInstance(mChoiceIds);
    mDialog.setTargetFragment(this, REQUEST_CHOICE);
    mFm = getActivity().getSupportFragmentManager();

    super.onCreate(savedInstanceState);
  }

  @Override public void resolveResponse(String arg0) {

    PlanList plan = new Gson().fromJson(arg0, PlanList.class);

    List<PlanCheckList> planList = plan.getDataList();
    setAdapter(planList);
  }

  private void setAdapter(List<PlanCheckList> list) {
    if (list == null) {
      list = new ArrayList<>();
    }
    mPlanApproveAdapter = new PlanApproveAdapter(getActivity(), list);
    setListAdapter(mPlanApproveAdapter);
    ((PlanApproveAdapter) getListAdapter()).notifyDataSetChanged();
  }

  /**
   * 计划审批选项
   */
  @Override public void onListItemClick(ListView l, View v, int position, long id) {
    mContent = mPlanApproveAdapter.getItem(position - 1);
    mId = mContent.getId();
    if (mDialog.isAdded()) {
      return; //or return false/true, based on where you are calling from
    }
    // 显示对话框.
    mDialog.show(mFm, "");
    super.onListItemClick(l, v, position, id);
  }

  protected void volleyPostSave(int i) {
    MyUtils.showDialogLoading(getActivity());
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_PLAN_APPROVE);
    HashMap<String, String> mPlan = new HashMap<>();

    // i=0代表同意。i=1代表返回。
    if (VALUE_APPROVEV == i) {
      // 执行同意操作
      mPlan.put("recStatus", "publish");
      mPlan.put("contentDesc", mAgree);
    }
    if (VALUE_OBJECT == i) {
      // 执行反对操作
      mPlan.put("recStatus", "backnew");
      mPlan.put("contentDesc", mAgainst);
    }

    mPlan.put("mainid", mId);
    LogUtil.i("params=" + mPlan.toString());
    mActivity.volleyPost(url, mPlan, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        try {
          MyUtils.dismissDialog();
          LogUtil.i("response=" + arg0);
          SuccessMessage successMessage = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == successMessage || null == successMessage.getResult()) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          String successType = successMessage.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();
            HintNumber.newInstance(getActivity()).reduce(HintNumber.APPROVE);
            volleyPost();
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {

      }
    });
  }

  // int item
  public static PlanApproveListFragment newInstance(int item) {
    Bundle bundle = new Bundle();
    bundle.putInt(EXTRA_TYPE, item);

    PlanApproveListFragment editFragment = new PlanApproveListFragment();
    editFragment.setArguments(bundle);
    return editFragment;
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    switch (requestCode) {
      case REQUEST_CHOICE:
        if (data != null) {
          int choice = data.getIntExtra(BaseSingleChoiceDialogFragment.EXTRA_RESULT, 0);
          //                volleyPostSave(choice);

          //查看详情
          if (2 == choice) {

            Intent intent = new Intent(getActivity(), PlanApproveDetailActivity.class);
            intent.putExtra(PlanApproveDetailFragment.EXTRA_CONTENT, mContent);
            startActivity(intent);
          } else {
            volleyPostSave(choice);
          }
        }
        break;

      default:
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
  }
}
